package org.walkerljl.practice.asyncparallel;

import org.walkerljl.practice.Task;

import java.util.List;
import java.util.concurrent.*;

/**
 * @author lijunlin
 */
public class CompletionServiceTest3 {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newCachedThreadPool();
        CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(executorService);
        int taskAmount = 10;
        List<Future> futures = new CopyOnWriteArrayList<Future>();
        for (int i = taskAmount; i > 0; i--) {
            futures.add(completionService.submit(new Task((long)i, i * 2)));
        }

        boolean isContinue = true;
        while (isContinue) {
            System.out.println("while loop");
          for (Future future : futures) {
              System.out.println("for loop");
              Integer result = null;
              try {
                  result = (Integer) future.get(1, TimeUnit.MILLISECONDS);
                  System.out.println("polling...");
              } catch (InterruptedException e) {
                  e.printStackTrace();
              } catch (ExecutionException e) {
                  e.printStackTrace();
              }  catch (TimeoutException ignore) {
                  //
              }

              try  {
                  if (result != null) {
                      futures.remove(future);
                      taskAmount --;
                      isContinue = false;
                      System.out.println(result.toString());
                      for (Future future1 : futures) {
                          future1.cancel(true);
                      }
                      break;

                  }
              } catch(Exception e) {
                  e.printStackTrace();
              }
          }
        }
    }
}
